import { defineStore } from 'pinia';
import { login, logout, register } from '../api/auth';
import router from '../router';

export const useUserStore = defineStore('user', {
  state: () => ({
    id: null,
    username: '',
    nickname: '',
    role: '',
    token: '',
    loading: false
  }),

  getters: {
    isLoggedIn: state => !!state.token,
    isFarmer: state => state.role === 'farmer',
    isBuyer: state => state.role === 'buyer',
    isAdmin: state => state.role === 'admin'
  },

  actions: {
    // 获取 token
    getToken() {
      return this.token;
    },
    
    // 登录
    async login(username, password) {
      this.loading = true;
      try {
        const response = await login({ username, password });
        
        if (response.success) {
          const userData = response.data;
          this.id = userData.id;
          this.username = userData.username;
          this.nickname = userData.nickname;
          this.role = userData.role;
          this.token = userData.token;
          
          // 根据角色跳转到不同的首页
          this.redirectToDashboard();
          return true;
        }
        return false;
      } catch (error) {
        console.error('登录失败', error);
        return false;
      } finally {
        this.loading = false;
      }
    },
    
    // 注册
    async register(userData) {
      this.loading = true;
      try {
        const response = await register(userData);
        if (response.success) {
          return true;
        }
        return false;
      } catch (error) {
        console.error('注册失败', error);
        return false;
      } finally {
        this.loading = false;
      }
    },
    
    // 退出登录
    async logout() {
      try {
        await logout();
      } catch (error) {
        console.error('退出登录失败', error);
      } finally {
        this.resetState();
        router.push('/auth/login');
      }
    },
    
    // 重置状态
    resetState() {
      this.id = null;
      this.username = '';
      this.nickname = '';
      this.role = '';
      this.token = '';
    },
    
    // 根据角色跳转到对应的首页
    redirectToDashboard() {
      if (this.role === 'farmer') {
        router.push('/farmer/dashboard');
      } else if (this.role === 'buyer') {
        router.push('/buyer/dashboard');
      } else if (this.role === 'admin') {
        router.push('/admin/dashboard');
      }
    }
  }
}); 